package com.zkjd.lingdong

import android.Manifest
import android.R
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.runtime.LaunchedEffect
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.zkjd.lingdong.repository.DeviceRepository
import com.zkjd.lingdong.service.BleService
import com.zkjd.lingdong.ui.function.AppSelectionScreen
import com.zkjd.lingdong.ui.function.FunctionScreen
import com.zkjd.lingdong.ui.function.FunctionScreenTwo
import com.zkjd.lingdong.ui.home.HomeScreen
import com.zkjd.lingdong.ui.home.HomeViewModel
import com.zkjd.lingdong.ui.led.LedColorScreen
import com.zkjd.lingdong.ui.pairing.PairingScreen
import com.zkjd.lingdong.ui.theme.LingDong2Theme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject


@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    
    @Inject
    lateinit var deviceRepository: DeviceRepository
    
    private val homeViewModel: HomeViewModel by viewModels()
    
    // 权限请求回调
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        var allGranted = true
        permissions.entries.forEach {
            if (!it.value) {
                allGranted = false
            }
        }
        
        if (allGranted) {
            // 权限都已授予，继续初始化
            lifecycleScope.launch {
                startBleService()
            }
        } else {
            // 显示权限请求失败的对话框
            showPermissionDeniedDialog()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //修改状态栏字体颜色，改为黑色
        //window.decorView.systemUiVisibility=View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            val window = window
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
//            window.statusBarColor = ContextCompat.getColor(this, R.color.white) // 设置状态栏颜色
//        }

        // 首先请求必要的权限
        requestRequiredPermissions()

        setContent {
            LingDong2Theme {
                val navController = rememberNavController()
                    
                // 从Intent中获取导航目标
                val navigateTo = intent.getStringExtra("navigate_to")
                
                LaunchedEffect(navigateTo) {
                    navigateTo?.let {
                        navController.navigate(it)
                    }
                }
                
                NavHost(navController = navController, startDestination = "home") {
                    composable("home") {
                        HomeScreen(
                            navController = navController,
                            viewModel = homeViewModel
                        )
                    }
                    composable("pairing") {
                        PairingScreen(navController)
                    }
                    composable("function/{deviceAddress}") { backStackEntry ->
                        val deviceAddress = backStackEntry.arguments?.getString("deviceAddress") ?: ""
                        FunctionScreenTwo(
                            navController = navController,
                            deviceMac = deviceAddress
                        )
                    }
                    composable("app_selection") {
                        AppSelectionScreen(navController)
                    }
                    composable("led_color/{deviceAddress}") { backStackEntry ->
                        val deviceAddress = backStackEntry.arguments?.getString("deviceAddress") ?: ""
                        LedColorScreen(
                            navController = navController,
                            deviceMac = deviceAddress
                        )
                    }
                }
            }
        }
    }


    /**
     * 请求应用所需的权限
     */
    private fun requestRequiredPermissions() {

        // 检查是否有悬浮窗权限
//        if (!Settings.canDrawOverlays(this)) {
//            val intent = Intent(
//                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                Uri.parse("package:${this.packageName}")
//            )
//            this.startActivity(intent)
//        }


        val permissionsToRequest = mutableListOf<String>()
        
        // 检查位置权限（蓝牙扫描必需）
        if (ContextCompat.checkSelfPermission(
                this, 
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        
        // Android 12及以上需要额外的蓝牙权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_SCAN
                ) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_SCAN)
            }
            
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_CONNECT)
            }
        } else {
            // Android 12以下版本需要的蓝牙权限
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH
                ) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH)
            }
            
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_ADMIN
                ) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_ADMIN)
            }
        }
        
        // Android 14需要的前台服务权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE
                ) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE)
            }
        }

        // WakeLock的地方请求权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.WAKE_LOCK)
        }

        //后台启动运用的权限,这个权限请请求不到，系统app才能申请到
        // permissionsToRequest.add(Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND);

        if (permissionsToRequest.isNotEmpty()) {
            // 请求所有必要权限
            requestPermissionLauncher.launch(permissionsToRequest.toTypedArray())
        } else {
            // 已有所有权限，直接继续
            lifecycleScope.launch {
                startBleService()
            }
        }
    }
    
    /**
     * 启动蓝牙服务
     */
    private fun startBleService() {
        try {
            val serviceIntent = Intent(this, BleService::class.java)
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent)
            } else {
                startService(serviceIntent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            // 尝试使用普通方式启动
            try {
                val serviceIntent = Intent(this, BleService::class.java)
                startService(serviceIntent)
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
        }
    }

    private fun showPermissionDeniedDialog() {
        AlertDialog.Builder(this)
            .setTitle("需要必要权限")
            .setMessage("为了确保妥妥贴能够正常工作，需要以下权限：\n\n" +
                    "• 蓝牙权限：用于连接设备\n" +
                    "• 位置权限：用于搜索蓝牙设备\n" +
                    "• 后台服务权限：保持设备连接\n\n" +
                    "请在设置中开启这些权限。")
            .setPositiveButton("去设置") { _, _ ->
                // 打开应用设置页面
                openAppSettings()
            }
            .setNegativeButton("退出应用") { _, _ ->
                finish()
            }
            .setCancelable(false)
            .show()
    }

    private fun openAppSettings() {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = Uri.fromParts("package", packageName, null)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            startActivity(intent)
        } catch (e: Exception) {
            // 如果无法打开应用设置，则打开系统设置
            startActivity(Intent(Settings.ACTION_SETTINGS))
        }
    }

    override fun onDestroy() {
        // 应用关闭时不停止服务，让服务继续在后台运行
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        
        // 每次恢复活动时，刷新设备数据
        homeViewModel.refreshDevices()
        
        // 每次回到应用时，确保服务在运行
        lifecycleScope.launch {
            // 不需要在onResume时重置连接状态，因为会导致刚连接上的设备被断开
            // 只需要确保服务在运行
            startBleService()
        }
    }
}

